#!/usr/bin/env bun

import { createBackup, listBackups, cleanupOldBackups, autoBackup } from './backup-database';
import { copyFile } from 'fs/promises';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const DB_PATH = join(__dirname, '../../database.sqlite');

/**
 * 恢复数据库从备份
 */
async function restoreFromBackup(backupPath: string): Promise<void> {
  try {
    // 先备份当前数据库
    console.log('🔄 备份当前数据库...');
    await createBackup();
    
    // 恢复数据库
    console.log('🔄 恢复数据库...');
    await copyFile(backupPath, DB_PATH);
    
    console.log('✅ 数据库恢复成功');
  } catch (error) {
    console.error('❌ 数据库恢复失败:', error);
    throw error;
  }
}

/**
 * 显示帮助信息
 */
function showHelp(): void {
  console.log(`
数据库管理工具

用法:
  bun run database-manager.ts <command> [options]

命令:
  backup              创建数据库备份
  list                列出所有备份
  cleanup [count]     清理旧备份，保留指定数量（默认10个）
  restore <backup>    从指定备份恢复数据库
  auto                执行自动备份（备份+清理）
  help                显示此帮助信息

示例:
  bun run database-manager.ts backup
  bun run database-manager.ts list
  bun run database-manager.ts cleanup 5
  bun run database-manager.ts restore database-backup-2024-01-01T12-00-00-000Z.sqlite
  bun run database-manager.ts auto
`);
}

/**
 * 格式化文件大小
 */
function formatFileSize(bytes: number): string {
  const sizes = ['B', 'KB', 'MB', 'GB'];
  if (bytes === 0) return '0 B';
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
  return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
}

/**
 * 主函数
 */
async function main(): Promise<void> {
  const args = process.argv.slice(2);
  const command = args[0];

  try {
    switch (command) {
      case 'backup':
        await createBackup();
        break;

      case 'list':
        console.log('📋 数据库备份列表:');
        const backups = await listBackups();
        if (backups.length === 0) {
          console.log('  暂无备份文件');
        } else {
          backups.forEach((backup, index) => {
            console.log(`  ${index + 1}. ${backup.name}`);
            console.log(`     大小: ${formatFileSize(backup.size)}`);
            console.log(`     日期: ${backup.date.toLocaleString('zh-CN')}`);
            console.log('');
          });
        }
        break;

      case 'cleanup':
        const keepCount = parseInt(args[1]) || 10;
        await cleanupOldBackups(keepCount);
        break;

      case 'restore':
        const backupName = args[1];
        if (!backupName) {
          console.error('❌ 请指定要恢复的备份文件名');
          process.exit(1);
        }
        
        const allBackups = await listBackups();
        const targetBackup = allBackups.find(b => b.name === backupName);
        
        if (!targetBackup) {
          console.error(`❌ 找不到备份文件: ${backupName}`);
          console.log('可用的备份文件:');
          allBackups.forEach(b => console.log(`  - ${b.name}`));
          process.exit(1);
        }
        
        await restoreFromBackup(targetBackup.path);
        break;

      case 'auto':
        await autoBackup();
        break;

      case 'help':
      case '--help':
      case '-h':
        showHelp();
        break;

      default:
        console.error(`❌ 未知命令: ${command}`);
        showHelp();
        process.exit(1);
    }
  } catch (error) {
    console.error('❌ 执行失败:', error);
    process.exit(1);
  }
}

// 运行主函数
if (import.meta.url === `file://${process.argv[1]}`) {
  main().catch(console.error);
}